<?php

/**
 * default actions.
 *
 * @package    stock
 * @subpackage default
 * @author     Your name here
 */
class monitorActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    $this->monitor_list = MonitorPeer::doSelect(new Criteria());
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new MonitorForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));
    $profitLimit = $_POST['profit'];
    $lowerLimit  = $_POST['lower'];
    $code = $_POST['code'];
    
    $c = new Criteria();
    $c->add(MonitorPeer::CODE, $code);
    if ($monitor = MonitorPeer::doSelectOne($c)) {
      return $this->renderText('Stock code monitor exists');
    }

    $data    = StockPeer::getData($code);
    if (!$data) {
      return $this->renderText('Incorrect stock code');
    }

    foreach ($data as $key=>$value) {
      $keyValue[] = "$key = '$value'";
    }

    if (!$stock = MyStockPeer::doSelectFromCode($code)) {
      $stock = new MyStock();
    }
    $stock->fromArray($data, BasePeer::TYPE_FIELDNAME);
    $stock->save();
    
    $monitor = new Monitor();
    $data    = array(
                    'Code' => $code,
                    'ProfitPrice' => $profitLimit,
                    'LossPrice'  => $lowerLimit,
                    'StockId'    => $stock->getId(),
                    'Status'     => 0
                    );
    $monitor->fromArray($data);
    $monitor->save();

    return sfView::NONE;
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($monitor = MonitorPeer::retrieveByPk($request->getParameter('id')), sprintf('Object monitor does not exist (%s).', $request->getParameter('id')));
    $this->form = new MonitorForm($monitor);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($monitor = MonitorPeer::retrieveByPk($request->getParameter('id')), sprintf('Object monitor does not exist (%s).', $request->getParameter('id')));
    $status = $request->getParameter('alarm');
    $profitPrice = $request->getParameter('profit');
    $lossPrice   = $request->getParameter('lower');

    $monitor->setProfitPrice($profitPrice);
    $monitor->setLossPrice($lossPrice);
    $monitor->setStatus($status);
    $monitor->save();

    return sfView::NONE;
  }

  public function executeDelete(sfWebRequest $request)
  {
    $this->forward404Unless($monitor = MonitorPeer::retrieveByPk($request->getParameter('id')), sprintf('Object monitor does not exist (%s).', $request->getParameter('id')));
    $monitor->delete();

    $this->redirect('monitor/index');
  }
}
